package container_usecase

import (
	"sync"

	"octopus/internal/domain/entities"
	"octopus/internal/domain/interfaces"
)

// ContainerService 容器服务实现
type ContainerService struct {
	repo        interfaces.ContainerRepository
	tasks       sync.Map // taskID -> *entities.Task
	taskManager interfaces.TaskManager
}

// NewContainerService 创建新的容器服务实例
func NewContainerService(repo interfaces.ContainerRepository, taskManager interfaces.TaskManager) *ContainerService {
	return &ContainerService{
		repo:        repo,
		tasks:       sync.Map{},
		taskManager: taskManager,
	}
}

// GetTask 获取任务状态
func (s *ContainerService) GetTask(taskID string) (*entities.Task, bool) {
	v, ok := s.tasks.Load(taskID)
	if !ok {
		return nil, false
	}
	return v.(*entities.Task), true
}

func (s *ContainerService) AsyncStopContainer(id string, notify func(task *entities.Task)) string {
	// 创建任务
	task := s.taskManager.CreateTask(id)

	// 存储初始任务状态
	s.taskManager.UpdateTaskStatus(task, entities.TaskPending)

	// 异步执行容器停止
	go func() {
		// 更新任务状态为运行中
	s.taskManager.UpdateTaskStatus(task, entities.TaskRunning)

		// 执行容器停止操作
		err := s.repo.Stop(id)
		if err != nil {
			task.Status = entities.TaskFailed
			task.Result = err.Error()
		} else {
			task.Status = entities.TaskSuccess
			task.Result = "Container stopped successfully"
		}
		// 更新任务状态并通知
	s.taskManager.UpdateTaskStatus(task, task.Status)
	s.taskManager.NotifyTaskCompletion(task, notify)
	}()

	return task.ID
}

// AsyncRestartContainer 异步重启容器，返回 taskID
func (s *ContainerService) AsyncRestartContainer(id string, notify func(task *entities.Task)) string {
	// 创建任务
	task := s.taskManager.CreateTask(id)

	// 存储初始任务状态
	s.taskManager.UpdateTaskStatus(task, entities.TaskPending)

	// 异步执行容器重启
	go func() {
		// 更新任务状态为运行中
	s.taskManager.UpdateTaskStatus(task, entities.TaskRunning)

		// 执行容器重启操作
		err := s.repo.Restart(id)
		if err != nil {
			task.Status = entities.TaskFailed
			task.Result = err.Error()
		} else {
			task.Status = entities.TaskSuccess
			task.Result = "Container restarted successfully"
		}
		// 更新任务状态并通知
	s.taskManager.UpdateTaskStatus(task, task.Status)
	s.taskManager.NotifyTaskCompletion(task, notify)
	}()

	return task.ID
}

// ListContainers 列出所有容器
func (s *ContainerService) ListContainers() ([]*entities.Container, error) {
	return s.repo.List()
}